#include "../include/user_list.h"

UserNode *user_list_init()
{
    UserNode *head = malloc(sizeof(UserNode));
    if(head == NULL)
    {
        printf("用户链表头结点创建失败\n");
        exit(1);
    }
    head->next = NULL;
    return head;
}

void user_list_insert_tail(UserNode *head, char *input)
{
    UserNode *new_node = malloc(sizeof(UserNode));
    if(new_node == NULL)
    {
        printf("用户链表新结点创建失败\n");
        exit(1);
    }

    memset(new_node->username, 0, sizeof(new_node->username));
    memset(new_node->password, 0, sizeof(new_node->password));
    memset(new_node->nickname, 0, sizeof(new_node->nickname));

    char *str = strtok(input, "@");
    strncpy(new_node->username, str, sizeof(new_node->username));
    str = strtok(NULL, "@");
    strncpy(new_node->password, str, sizeof(new_node->password));
    str = strtok(NULL, "@");
    strncpy(new_node->nickname, str, sizeof(new_node->nickname));

    UserNode *p = head;
    while(p->next != NULL)
    {
        p = p->next;
    }

    new_node->next = p->next;
    p->next = new_node;
}

char *find_user(UserNode *head, char *username, const char *password)
{
    UserNode *p = head->next;
    while(p != NULL)
    {
        if(strcmp(p->username, username) == 0 && strcmp(p->password, password) == 0)
        {
            return p->nickname;
        }
        p = p->next;
    }
    return NULL;
}